package com.example.demo.service;


import com.example.demo.entity.Course;
import com.example.demo.mapper.CourseMapper;
import com.example.demo.mapper.StudentCourseMapper;
import com.example.demo.entity.StudentCourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class StudentCourseService {

    @Autowired
    private StudentCourseMapper mapper;
    @Autowired
    private CourseMapper courseMapper;

    // 选课操作
    public StudentCourse enrollCourse(String studentId, String courseId) {
        // 1. 检查是否已选课（防止重复选课，利用 uk_student_course 唯一键）
        if (mapper.findByStudentIdAndCourseId(studentId, courseId).isPresent()) {
            throw new IllegalStateException("重复选课：该学生已选该课程。");
        }

        StudentCourse enrollment = new StudentCourse();
        enrollment.setStudentId(studentId);
        enrollment.setCourseId(courseId);
        enrollment.setEnrollmentStatus("enrolled"); // 初始状态为 enrolled
        enrollment.setEnrollmentDate(LocalDate.now()); // 设置选课日期

        // 2. 插入记录
        try {
            mapper.insert(enrollment);
            return enrollment; // 返回包含自增 ID 的记录
        } catch (Exception e) {
            // 捕获外键约束失败（studentId 或 courseId 不存在）
            throw new RuntimeException("选课失败，请检查学生学号或课程ID是否存在。", e);
        }
    }

    // 根据学生ID查找所有选课记录
    public List<StudentCourse> findCoursesByStudentId(String studentId) {
        return mapper.findByStudentId(studentId);
    }

    // 退课/删除选课记录
    public boolean dropCourse(Integer id) {
        return mapper.deleteById(id) > 0;
    }

    // 更新课程成绩（教师操作）
    public boolean updateScore(String studentId, String courseId, BigDecimal score) {
        Optional<StudentCourse> recordOpt = mapper.findByStudentIdAndCourseId(studentId, courseId);

        if (recordOpt.isEmpty()) {
            return false; // 记录不存在
        }

        StudentCourse record = recordOpt.get();
        record.setScore(score);
        record.setEnrollmentStatus("completed"); // 成绩录入后，状态通常改为 completed

        return mapper.update(record) > 0;
    }
    public List<Course> findEnrolledCoursesBySemester(String studentId, String semesterId) {
        // 1. 查询学生该学期的选课记录
        List<StudentCourse> enrollments = mapper.findByStudentIdAndSemester(studentId, semesterId);
        if (enrollments.isEmpty()) {
            return Collections.emptyList(); // 无选课记录返回空列表
        }
        // 2. 提取课程ID列表
        List<String> courseIds = enrollments.stream()
                .map(StudentCourse::getCourseId)
                .collect(Collectors.toList());
        // 3. 查询对应的课程信息

        return courseMapper.findByIdsAndSemester(courseIds, semesterId);
    }
}